using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Acms.AcmsControls
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:UserDetailsControl runat=server></{0}:UserDetailsControl>")]
    public class UserDetailsControl : CompositeControl
    {
        public enum Mode
        {
            Display,
            Edit,
            ChangePassword
        }

        TextBox txtUsername = new TextBox();
        Label lblUserName = new Label();
        RequiredFieldValidator valUsernameReq = new RequiredFieldValidator();
        RegularExpressionValidator valUsernameFormat = new RegularExpressionValidator();

        TextBox txtOriginalPassword = new TextBox();
        RequiredFieldValidator valOriginalPasswordReq = new RequiredFieldValidator();

        TextBox txtPassword = new TextBox();
        RequiredFieldValidator valPasswordReq = new RequiredFieldValidator();
        RegularExpressionValidator valPasswordFormat = new RegularExpressionValidator();

        TextBox txtConfirmPassword = new TextBox();
        RequiredFieldValidator valConfirmPasswordReq = new RequiredFieldValidator();
        CompareValidator valConfirmPasswordMatch = new CompareValidator();

        TextBox txtEmail = new TextBox();
        Label lblEmail = new Label();
        RequiredFieldValidator valEmailReq = new RequiredFieldValidator();
        RegularExpressionValidator valEmailFormat = new RegularExpressionValidator();

        TextBox txtFirstName = new TextBox();
        Label lblFirstName = new Label();
        RequiredFieldValidator valFirstNameReq = new RequiredFieldValidator();

        TextBox txtLastName = new TextBox();
        Label lblLastName = new Label();
        RequiredFieldValidator valLastNameReq = new RequiredFieldValidator();

        TextBox txtDateOfBirth = new TextBox();
        Label lblDateOfBirth = new Label();
        RequiredFieldValidator valDOBReq = new RequiredFieldValidator();
        RangeValidator valDOBRange = new RangeValidator();

        RadioButton rdoGenderMale = new RadioButton();
        RadioButton rdoGenderFemale = new RadioButton();
        Label lblGender = new Label();
        Acms.WebControls.CheckedRequiredValidator valGenderReq = new Acms.WebControls.CheckedRequiredValidator();

        TextBox txtAddress1 = new TextBox();
        Label lblAddress1 = new Label();
        RequiredFieldValidator valAddress1Req = new RequiredFieldValidator();

        TextBox txtAddress2 = new TextBox();
        Label lblAddress2 = new Label();

        TextBox txtTown = new TextBox();
        Label lblTown = new Label();
        RequiredFieldValidator valTownReq = new RequiredFieldValidator();

        TextBox txtPostCode = new TextBox();
        Label lblPostCode = new Label();
        RequiredFieldValidator valPostCodeReq = new RequiredFieldValidator();

        TextBox txtMobile = new TextBox();
        Label lblMobile = new Label();
        RequiredFieldValidator valMobileReq = new RequiredFieldValidator();


        Button btnSaveDetails = new Button();
        Button btnEditDetails = new Button();
        Button btnCancelDetails = new Button();
        Button btnChangePassword = new Button();
        Button btnSavePassword = new Button();
        Button btnCancelPassword = new Button();

        private ITemplate customEditFields;
        [System.Web.UI.TemplateInstance(TemplateInstance.Single)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [Browsable(false)]
        public ITemplate CustomEditFields
        {
            get { return customEditFields; }
            set { customEditFields = value; }
        }

        private Control customEditFieldsContainer;

        private ITemplate customDisplayFields;
        [System.Web.UI.TemplateInstance(TemplateInstance.Single)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [Browsable(false)]
        public ITemplate CustomDisplayFields
        {
            get { return customDisplayFields; }
            set { customDisplayFields = value; }
        }

        private Control customDisplayFieldsContainer;


        private string errorMessageClass = "errorMessage";
        public string ErrorMessageClass
        {
            get { return errorMessageClass; }
            set { errorMessageClass = value; }
        }

        private string usernameValidationExpression = @"^[a-zA-Z0-9]{1}[a-zA-Z0-9\S]{3,12}[a-zA-Z0-9]{1}$";
        public string UsernameValidationExpression
        {
            get { return usernameValidationExpression; }
            set
            {
                usernameValidationExpression = value;
                if (valUsernameFormat != null)
                    valUsernameFormat.ValidationExpression = value;
            }
        }

        private string userNameFormatErrorMessage = "Username must be between 5 and 14 characters, must start and end with a alphanumeric character and cannot contain spaces.";
        public string UserNameFormatErrorMessage
        {
            get { return userNameFormatErrorMessage; }
            set { userNameFormatErrorMessage = value; }
        }

        private string passwordValidationExpression = @"^[a-zA-Z][\S]{4,13}$";
        public string PasswordValidationExpression
        {
            get { return passwordValidationExpression; }
            set
            {
                passwordValidationExpression = value;
                if (valPasswordFormat != null)
                    valPasswordFormat.ValidationExpression = value;
            }
        }

        private string passwordFormatErrorMessage = "Password must start with a letter and be between 5 and 14 characters. No spaces are allowed.";
        public string PasswordFormatErrorMessage
        {
            get { return passwordFormatErrorMessage; }
            set { passwordFormatErrorMessage = value; }
        }


        private string emailValidationExpression = @"^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z+])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$";
        public string EmailValidationExpression
        {
            get { return emailValidationExpression; }
            set
            {
                emailValidationExpression = value;
                if (valEmailFormat != null)
                    valEmailFormat.ValidationExpression = value;
            }
        }

        private string requiredErrorMessage = "*Required";
        public string RequiredErrorMessage
        {
            get { return requiredErrorMessage; }
            set { requiredErrorMessage = value; }
        }

        private Mode currentMode = Mode.Display;
        public Mode CurrentMode
        {
            get { return currentMode; }
        }

        private bool requiresDataBinding = true;

        private object concurencyId;

        bool duplicateEmail;
        bool duplicateUsername;
        bool failedToSetPassword;

        bool rdoGenderMaleChecked;
        bool rdoGenderFemaleChecked;
        protected override object SaveViewState()
        {
            ViewState["UsernameValidationExpression"] = UsernameValidationExpression;
            ViewState["UserNameFormatErrorMessage"] = UserNameFormatErrorMessage;
            ViewState["PasswordValidationExpression"] = PasswordValidationExpression;
            ViewState["PasswordFormatErrorMessage"] = PasswordFormatErrorMessage;
            ViewState["EmailValidationExpression"] = EmailValidationExpression;
            ViewState["RequiredErrorMessage"] = RequiredErrorMessage;
            ViewState["CurrentMode"] = currentMode;
            ViewState["RequiresDataBinding"] = requiresDataBinding;
            ViewState["ConcurencyId"] = concurencyId;
            ViewState["GenderMaleChecked"] = rdoGenderMaleChecked;
            ViewState["GenderFemaleChecked"] = rdoGenderFemaleChecked;
            return base.SaveViewState();
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            UsernameValidationExpression = ViewState["UsernameValidationExpression"] as string;
            UserNameFormatErrorMessage = ViewState["UserNameFormatErrorMessage"] as string;
            PasswordValidationExpression = ViewState["PasswordValidationExpression"] as string;
            PasswordFormatErrorMessage = ViewState["PasswordFormatErrorMessage"] as string;
            EmailValidationExpression = ViewState["EmailValidationExpression"] as string;
            RequiredErrorMessage = ViewState["RequiredErrorMessage"] as string;
            currentMode = (Mode)ViewState["CurrentMode"];
            if (ViewState["RequiresDataBinding"] is bool)
               requiresDataBinding = (bool)ViewState["RequiresDataBinding"];
           concurencyId = ViewState["concurencyId"];
           if (ViewState["GenderMaleChecked"] is bool)
               rdoGenderMaleChecked = (bool)ViewState["GenderMaleChecked"];
           if (ViewState["GenderFemaleChecked"] is bool)
               rdoGenderFemaleChecked = (bool)ViewState["GenderFemaleChecked"];
       }
        
        protected override void CreateChildControls()
        {
            this.Controls.Clear();

            //init buttons first as validation group needed for validators
            InitButton(btnCancelDetails, "btnCancelDetails", "Cancel", false);
            InitButton(btnCancelPassword, "btnCancelPassword", "Cancel", false);
            InitButton(btnChangePassword, "btnChangePassword", "Change Password", false);
            InitButton(btnEditDetails, "btnEditDetails", "Edit", false);
            InitButton(btnSaveDetails, "btnSaveDetails", "Save", true);
            InitButton(btnSavePassword, "btnSavePassword", "Save", true);


            InitControl(lblUserName, "lblUserName");
            InitControl(txtUsername, "txtUsername");
            InitValidator(valUsernameReq, txtUsername, RequiredErrorMessage, btnSaveDetails);
            InitValidator(valUsernameFormat, txtUsername, UserNameFormatErrorMessage, btnSaveDetails);
            valUsernameFormat.ValidationExpression = UsernameValidationExpression;

            InitControl(txtOriginalPassword, "txtOriginalPassword");
            txtOriginalPassword.TextMode = TextBoxMode.Password;
            InitValidator(valOriginalPasswordReq, txtOriginalPassword, RequiredErrorMessage, btnSavePassword);

            InitControl(txtPassword, "txtPassword");
            txtPassword.TextMode = TextBoxMode.Password;
            InitValidator(valPasswordReq, txtPassword, RequiredErrorMessage, btnSavePassword);
            InitValidator(valPasswordFormat, txtPassword, PasswordFormatErrorMessage, btnSavePassword);
            valPasswordFormat.ValidationExpression = PasswordValidationExpression;

            InitControl(txtConfirmPassword, "txtConfirmPassword");
            txtConfirmPassword.TextMode = TextBoxMode.Password;
            InitValidator(valConfirmPasswordReq, txtConfirmPassword, RequiredErrorMessage, btnSavePassword);
            InitValidator(valConfirmPasswordMatch, txtConfirmPassword, "Passwords do not match.", btnSavePassword);
            valConfirmPasswordMatch.ControlToCompare = txtPassword.ID;
            valConfirmPasswordMatch.Operator = ValidationCompareOperator.Equal;

            InitControl(lblEmail, "lblEmail");
            InitControl(txtEmail, "txtEmail");
            InitValidator(valEmailReq, txtEmail, RequiredErrorMessage, btnSaveDetails);
            InitValidator(valEmailFormat, txtEmail, "Invalid Email Address.", btnSaveDetails);
            valEmailFormat.ValidationExpression = EmailValidationExpression;

            InitControl(lblFirstName, "lblFirstName");
            InitControl(txtFirstName, "txtFirstName");
            InitValidator(valFirstNameReq, txtFirstName, RequiredErrorMessage, btnSaveDetails);

            InitControl(lblLastName, "lblLastName");
            InitControl(txtLastName, "txtLastName");
            InitValidator(valLastNameReq, txtLastName, RequiredErrorMessage, btnSaveDetails);

            InitControl(lblDateOfBirth, "lblDateOfBirth");
            InitControl(txtDateOfBirth, "txtDateOfBirth");
            InitValidator(valDOBReq, txtDateOfBirth, RequiredErrorMessage, btnSaveDetails);
            InitValidator(valDOBRange, txtDateOfBirth, "Invalid Date of Birth", btnSaveDetails);
            valDOBRange.MinimumValue = DateTime.Today.AddYears(-100).ToString("yyyy/MM/dd");
            valDOBRange.MaximumValue = DateTime.Today.AddYears(-1).ToString("yyyy/MM/dd");
            valDOBRange.CultureInvariantValues = true;
            valDOBRange.Type = ValidationDataType.Date;

            InitControl(lblGender, "lblGender");
            InitControl(rdoGenderMale, "rdoGenderMale");
            rdoGenderMale.GroupName = string.Concat(this.ClientID, "gender");
            InitControl(rdoGenderFemale, "rdoGenderFemale");
            rdoGenderFemale.GroupName = string.Concat(this.ClientID, "gender");
            InitValidator(valGenderReq, null, RequiredErrorMessage, btnSaveDetails);
            valGenderReq.ControlsToValidate = new string[] { rdoGenderMale.ID, rdoGenderFemale.ID };

            InitControl(lblAddress1, "lblAddress1");
            InitControl(txtAddress1, "txtAddress1");
            InitValidator(valAddress1Req, txtAddress1, RequiredErrorMessage, btnSaveDetails);

            InitControl(lblAddress2, "lblAddress2");
            InitControl(txtAddress2, "txtAddress2");

            InitControl(lblTown, "lblTown");
            InitControl(txtTown, "txtTown");
            InitValidator(valTownReq, txtTown, RequiredErrorMessage, btnSaveDetails);

            InitControl(txtPostCode, "lblPostCode");
            InitControl(txtPostCode, "txtPostCode");
            InitValidator(valPostCodeReq, txtPostCode, RequiredErrorMessage, btnSaveDetails);

            InitControl(lblMobile, "lblMobile");
            InitControl(txtMobile, "txtMobile");
            InitValidator(valMobileReq, txtMobile, RequiredErrorMessage, btnSaveDetails);

            if (CustomDisplayFields != null)
            {
                customDisplayFieldsContainer = new PlaceHolder();
                this.Controls.Add(customDisplayFieldsContainer);
                CustomDisplayFields.InstantiateIn(customDisplayFieldsContainer);
            }

            if (CustomEditFields != null)
            {
                customEditFieldsContainer = new PlaceHolder();
                this.Controls.Add(customEditFieldsContainer);
                CustomEditFields.InstantiateIn(customEditFieldsContainer);
            }
            btnCancelDetails.Click += new EventHandler(btnCancel_Click);
            btnCancelPassword.Click += new EventHandler(btnCancel_Click);
            btnChangePassword.Click += new EventHandler(btnChangePassword_Click);
            btnEditDetails.Click += new EventHandler(btnEditDetails_Click);
            btnSaveDetails.Click += new EventHandler(btnSaveDetails_Click);
            btnSavePassword.Click += new EventHandler(btnSavePassword_Click);
            base.CreateChildControls();
        }

        //dummy event used to enure text box saves text vaule even if not shown
        //see SaveTextViewState in google for more info
        void txt_TextChanged(object sender, EventArgs e)
        {
        }

        void btnSavePassword_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                Acms.Bll.UserIdentity identity = Page.User.Identity as Acms.Bll.UserIdentity;
                if (identity != null)
                {
                    Acms.Bll.UserSecurity user = Acms.Bll.UserSecurity.GetById(identity.User.Id);
                    if (user != null)
                    {
                        failedToSetPassword = !user.SetPassword(txtOriginalPassword.Text, txtPassword.Text);
                        if (!failedToSetPassword)
                        {
                            user.Update();
                            currentMode = Mode.Display;
                        }
                    }
                }
            }
        }

        void btnSaveDetails_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                Acms.Bll.UserIdentity identity = Page.User.Identity as Acms.Bll.UserIdentity;
                if(identity != null)
                {
                    Acms.Bll.UserSecurity user = Acms.Bll.UserSecurity.GetById(identity.User.Id);
                    if(user != null)
                    {
                        user.CheckConcurent(concurencyId);
                        user.Address1 = txtAddress1.Text;
                        user.Address2 = txtAddress2.Text;
                        try
                        {
                            user.DateOfBirth = DateTime.Parse(txtDateOfBirth.Text);
                        }
                        catch
                        {
                        }
                        user.EmailAddress = txtEmail.Text;
                        user.FirstName = txtFirstName.Text;
                        if(rdoGenderMale.Checked)
                            user.Gender = Acms.Bll.User.Genders.Male;
                        else
                            user.Gender = Acms.Bll.User.Genders.Female;
                        user.LastName = txtLastName.Text;
                        user.MobileTel = txtMobile.Text;
                        user.PostCode = txtPostCode.Text;
                        user.Town = txtTown.Text;
                        user.UserName = txtUsername.Text;

                        OnUserUpdating(new UserRegisterEventArgs(user));

                        try
                        {
                            user.Update();
                        }
                        catch(Acms.Exceptions.DuplicateEmailException)
                        {
                            duplicateEmail = true;
                        }
                        catch(Acms.Exceptions.DuplicateUsernameException)
                        {
                            duplicateUsername = true;
                        }
                    }

                }
                
                if(!duplicateEmail && !duplicateUsername)
                {
                    identity.RefreshUser();
                    currentMode = Mode.Display;
                    DataBind();
                }
            }
        }

        protected void OnUserUpdating(UserRegisterEventArgs e)
        {
            if (UserUpdating != null)
            {
                UserUpdating(this, e);
            }
        }

        public event EventHandler<UserRegisterEventArgs> UserUpdating;

        void btnEditDetails_Click(object sender, EventArgs e)
        {
            currentMode = Mode.Edit;
        }

        void btnChangePassword_Click(object sender, EventArgs e)
        {
            currentMode = Mode.ChangePassword;
        }

        void btnCancel_Click(object sender, EventArgs e)
        {
            currentMode = Mode.Display; 
        }

        private void InitControl(Control ctrl, string id)
        {
            ctrl.ID = id;
            this.Controls.Add(ctrl);
            if (ctrl is TextBox)
            {
                ((TextBox)ctrl).TextChanged += new EventHandler(txt_TextChanged);
            }
            else if (ctrl is RadioButton)
            {
                ((RadioButton)ctrl).CheckedChanged += new EventHandler(txt_TextChanged);
            }
        }

        private void InitButton(Button btn, string id, string text, bool causesValidation)
        {
            btn.ID = id;
            btn.Text = text;
            btn.CausesValidation = causesValidation;
            btn.ValidationGroup = string.Concat(this.ClientID, btn.ID);
            this.Controls.Add(btn);
        }

        private void InitValidator(BaseValidator val, Control controlToValidate, string errorMessage, Button btn)
        {
            val.ErrorMessage = errorMessage;
            if (controlToValidate != null)
            {
                val.ControlToValidate = controlToValidate.ID;
            }
            val.ValidationGroup = btn.ValidationGroup;
            val.Display = ValidatorDisplay.Dynamic;
            this.Controls.Add(val);
        }

        public override void DataBind()
        {
            requiresDataBinding = false;
            if (Page != null && Page.Request != null && Page.Request.IsAuthenticated)
            {
                if (Page.User.Identity is Acms.Bll.UserIdentity)
                {
                    Acms.Bll.User user = ((Acms.Bll.UserIdentity)Page.User.Identity).User;
                    lblUserName.Text = txtUsername.Text = user.UserName;
                    lblEmail.Text = txtEmail.Text = user.EmailAddress;
                    lblFirstName.Text = txtFirstName.Text = user.FirstName;
                    lblLastName.Text = txtLastName.Text = user.LastName;
                    lblAddress1.Text = txtAddress1.Text = user.Address1;
                    lblAddress2.Text = txtAddress2.Text = user.Address2;
                    lblTown.Text = txtTown.Text = user.Town;
                    lblPostCode.Text = txtPostCode.Text = user.PostCode;
                    lblMobile.Text = txtMobile.Text = user.MobileTel;
                    if (user.Gender == Acms.Bll.User.Genders.Male)
                    {
                        rdoGenderMale.Checked = rdoGenderMaleChecked = true;
                        rdoGenderFemaleChecked = false;
                        lblGender.Text = "Male";
                    }
                    else if (user.Gender == Acms.Bll.User.Genders.Female)
                    {
                        rdoGenderFemale.Checked = rdoGenderFemaleChecked = true;
                        rdoGenderMaleChecked = false;
                        lblGender.Text = "Female";
                    }
                    if (user.DateOfBirth != DateTime.MinValue)
                        lblDateOfBirth.Text = txtDateOfBirth.Text = user.DateOfBirth.ToShortDateString();
                    if (customDisplayFieldsContainer != null)
                        customDisplayFieldsContainer.DataBind();
                    if (customEditFieldsContainer != null)
                        customEditFieldsContainer.DataBind();
                }
            }
            else if (Page != null && Page.Request != null && !Page.Request.IsAuthenticated)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (requiresDataBinding)
            {
                DataBind();
            }

            lblUserName.Visible = CurrentMode == Mode.Display;
            lblEmail.Visible = CurrentMode == Mode.Display;
            lblFirstName.Visible = CurrentMode == Mode.Display;
            lblLastName.Visible = CurrentMode == Mode.Display;
            lblAddress1.Visible = CurrentMode == Mode.Display;
            lblAddress2.Visible = CurrentMode == Mode.Display;
            lblTown.Visible = CurrentMode == Mode.Display;
            lblPostCode.Visible = CurrentMode == Mode.Display;
            lblMobile.Visible = CurrentMode == Mode.Display;

            txtEmail.Visible = CurrentMode == Mode.Edit;
            txtFirstName.Visible = CurrentMode == Mode.Edit;
            txtLastName.Visible = CurrentMode == Mode.Edit;
            txtAddress1.Visible = CurrentMode == Mode.Edit;
            txtAddress2.Visible = CurrentMode == Mode.Edit;
            txtTown.Visible = CurrentMode == Mode.Edit;
            txtPassword.Visible = CurrentMode == Mode.Edit;
            txtMobile.Visible = CurrentMode == Mode.Edit;

            txtPassword.Visible = CurrentMode == Mode.ChangePassword;
            txtConfirmPassword.Visible = CurrentMode == Mode.ChangePassword;


            if (!rdoGenderFemale.Checked && !rdoGenderFemale.Checked)
            {
                rdoGenderMale.Checked = rdoGenderMaleChecked;
                rdoGenderFemale.Checked = rdoGenderFemaleChecked;
            }

            if (customDisplayFieldsContainer != null)
                customDisplayFieldsContainer.Visible = CurrentMode == Mode.Display;

            if (customEditFieldsContainer != null)
                customEditFieldsContainer.Visible = CurrentMode == Mode.Edit; 
            
            base.OnPreRender(e);
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            //wrapper div
            if (CurrentMode == Mode.ChangePassword)
            {
                writer.AddAttribute("OnKeyPress", string.Format("javascript:return WebForm_FireDefaultButton(event, '{0}')", btnSavePassword.ClientID));
            }
            else if (CurrentMode == Mode.Edit)
            {
                writer.AddAttribute("OnKeyPress", string.Format("javascript:return WebForm_FireDefaultButton(event, '{0}')", btnSaveDetails.ClientID));
            }
            writer.RenderBeginTag(HtmlTextWriterTag.Div);


            if (duplicateEmail || duplicateUsername || failedToSetPassword)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, ErrorMessageClass);
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                if (duplicateEmail)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    writer.Write("This email address belongs to another user.");
                    writer.RenderEndTag();
                }
                if (duplicateUsername)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    writer.Write("This username belongs to another user.");
                    writer.RenderEndTag();
                }
                if (failedToSetPassword)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    writer.Write("Incorrect original password.");
                    writer.RenderEndTag();
                }
                writer.RenderEndTag();
            }

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "register");
            writer.RenderBeginTag(HtmlTextWriterTag.Ul);
            if (CurrentMode == Mode.Display || CurrentMode == Mode.Edit)
            {
                RenderUsername(writer);
                RenderEmail(writer);
                RenderFirstName(writer);
                RenderLastName(writer);
                RenderDateOfBirth(writer);
                RenderGender(writer);
                RenderAddress(writer);
                RenderMobile(writer);
                if (CurrentMode == Mode.Display && customDisplayFieldsContainer != null)
                    customDisplayFieldsContainer.RenderControl(writer);
                if (CurrentMode == Mode.Edit && customEditFieldsContainer != null)
                    customEditFieldsContainer.RenderControl(writer);

                RenderButtons(writer);

            }
            else if (CurrentMode == Mode.ChangePassword)
            {
                RenderItemWrapperStart(writer, "originalPassword");
                RenderLabel("Original Password:", txtOriginalPassword, writer);
                txtOriginalPassword.RenderControl(writer);
                valOriginalPasswordReq.RenderControl(writer);
                RenderItemWrapperEnd(writer);

                RenderItemWrapperStart(writer, "password");
                RenderLabel("New Password:", txtPassword, writer);
                txtPassword.RenderControl(writer);
                valPasswordReq.RenderControl(writer);
                valPasswordFormat.RenderControl(writer);
                RenderItemWrapperEnd(writer);
                
                RenderItemWrapperStart(writer, "confirmPassword");
                RenderLabel("Confirm New Password:", txtConfirmPassword, writer);
                txtConfirmPassword.RenderControl(writer);
                valConfirmPasswordReq.RenderControl(writer);
                valConfirmPasswordMatch.RenderControl(writer);
                RenderItemWrapperEnd(writer); 
                RenderButtons(writer);
            }
            writer.RenderEndTag();
            writer.RenderEndTag();

        }

        private void RenderItemWrapperStart(HtmlTextWriter writer, string cssClass)
        {
            string tmp = string.Concat("register ", cssClass);
            writer.AddAttribute(HtmlTextWriterAttribute.Class, tmp.Trim());
            writer.RenderBeginTag(HtmlTextWriterTag.Li);

        }

        private void RenderItemWrapperEnd(HtmlTextWriter writer)
        {
            writer.RenderEndTag();
        }


        private void RenderLabel(string text, Control associatedControl, HtmlTextWriter writer)
        {
            if (associatedControl != null)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.For, associatedControl.ClientID);
                writer.RenderBeginTag(HtmlTextWriterTag.Label);
            }
            else
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Label);
            }
            writer.Write(text);
            writer.RenderEndTag();
        }

        private void RenderUsername(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "username");
            if (CurrentMode == Mode.Display)
            {
                RenderLabel("Username:", lblUserName, writer);
                lblUserName.RenderControl(writer);
            }
            else
            {
                RenderLabel("Username:", txtUsername, writer);
                txtUsername.RenderControl(writer);
                valUsernameReq.RenderControl(writer);
                valUsernameFormat.RenderControl(writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderEmail(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "email");
            if (CurrentMode == Mode.Display)
            {
                RenderLabel("Email Address:", lblEmail, writer);
                lblEmail.RenderControl(writer);
            }
            else
            {
                RenderLabel("Email Address:", txtEmail, writer);
                txtEmail.RenderControl(writer);
                valEmailReq.RenderControl(writer);
                valEmailFormat.RenderControl(writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderFirstName(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "firstName");
            if (CurrentMode == Mode.Display)
            {
                RenderLabel("First Name:", lblFirstName, writer);
                lblFirstName.RenderControl(writer);
            }
            else
            {
                RenderLabel("First Name:", txtFirstName, writer);
                txtFirstName.RenderControl(writer);
                valFirstNameReq.RenderControl(writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderLastName(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "lastName");
            if (CurrentMode == Mode.Display)
            {
                RenderLabel("Last Name:", lblLastName, writer);
                lblLastName.RenderControl(writer);
            }
            else
            {
                RenderLabel("Last Name:", txtLastName, writer);
                txtLastName.RenderControl(writer);
                valLastNameReq.RenderControl(writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderDateOfBirth(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "dob");
            if (CurrentMode == Mode.Display)
            {
                RenderLabel("Date Of Birth:", lblDateOfBirth, writer);
                lblDateOfBirth.RenderControl(writer);
            }
            else
            {
                RenderLabel("Date Of Birth:", txtDateOfBirth, writer);
                txtDateOfBirth.RenderControl(writer);
                writer.Write("dd/mm/yyyy");
                valDOBReq.RenderControl(writer);
                valDOBRange.RenderControl(writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderGender(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "gender");
            if (CurrentMode == Mode.Display)
            {
                RenderLabel("Gender:", lblGender, writer);
                lblGender.RenderControl(writer);
            }
            else
            {
                //writer.RenderBeginTag(HtmlTextWriterTag.Span);
                //writer.Write("Gender:");
                //writer.RenderEndTag();

                RenderLabel("Male", rdoGenderMale, writer);
                rdoGenderMale.RenderControl(writer);
                RenderLabel("Female", rdoGenderFemale, writer);
                rdoGenderFemale.RenderControl(writer);
                valGenderReq.RenderControl(writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private string addressSpacer = ", ";
        public string AddressSpacer
        {
            get { return addressSpacer; }
            set { addressSpacer = value; }
        }
	

        private void RenderAddress(HtmlTextWriter writer)
        {
            if (CurrentMode == Mode.Display)
            {
                RenderItemWrapperStart(writer, "address");
                RenderLabel("Address:", null, writer);
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                if (!string.IsNullOrEmpty(lblAddress1.Text))
                {
                    lblAddress1.RenderControl(writer);
                    writer.Write(AddressSpacer);
                }
                if (!string.IsNullOrEmpty(lblAddress2.Text))
                {
                    lblAddress2.RenderControl(writer);
                    writer.Write(AddressSpacer);
                }
                if (!string.IsNullOrEmpty(lblTown.Text))
                {
                    lblTown.RenderControl(writer);
                    writer.Write(AddressSpacer);
                }
                if (!string.IsNullOrEmpty(lblPostCode.Text))
                {
                    lblPostCode.RenderControl(writer);
                }
                RenderItemWrapperEnd(writer);
                writer.RenderEndTag();
            }
            else
            {
                RenderItemWrapperStart(writer, "address1");
                RenderLabel("Address (Line 1):", txtAddress1, writer);
                txtAddress1.RenderControl(writer);
                valAddress1Req.RenderControl(writer);
                RenderItemWrapperEnd(writer);

                RenderItemWrapperStart(writer, "address2");
                RenderLabel("Address (Line 2):", txtAddress2, writer);
                txtAddress2.RenderControl(writer);
                RenderItemWrapperEnd(writer);

                RenderItemWrapperStart(writer, "town");
                RenderLabel("Town / City:", txtTown, writer);
                txtTown.RenderControl(writer);
                valTownReq.RenderControl(writer);
                RenderItemWrapperEnd(writer);

                RenderItemWrapperStart(writer, "postcode");
                RenderLabel("PostCode:", txtPostCode, writer);
                txtPostCode.RenderControl(writer);
                valPostCodeReq.RenderControl(writer);
                RenderItemWrapperEnd(writer);
            }
        }

        private void RenderMobile(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "mobile tel");
            if (CurrentMode == Mode.Display)
            {
                RenderLabel("Mobile:", lblMobile, writer);
                lblMobile.RenderControl(writer);
            }
            else
            {
                RenderLabel("Mobile:", txtMobile, writer);
                txtMobile.RenderControl(writer);
                valMobileReq.RenderControl(writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderButtons(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "buttons");
            if (CurrentMode == Mode.Edit)
            {
                btnSaveDetails.RenderControl(writer);
                btnCancelDetails.RenderControl(writer);
            }
            else if (CurrentMode == Mode.Display)
            {
                btnEditDetails.RenderControl(writer);
                btnChangePassword.RenderControl(writer);
            }
            else if (CurrentMode == Mode.ChangePassword)
            {
                btnSavePassword.RenderControl(writer);
                btnCancelPassword.RenderControl(writer);
            }
            RenderItemWrapperEnd(writer);
        }

       /* 

        


        

        private ITemplate customFields;
        [System.Web.UI.TemplateInstance(TemplateInstance.Single)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [Browsable(false)]
        public ITemplate CustomFields
        {
            get { return customFields; }
            set { customFields = value; }
        }

        private Control customFieldsContainer;

        protected override void CreateChildControls()
        {
            this.Controls.Clear();

            username = InitTextBox("username");

            valUsernameReq = new RequiredFieldValidator();
            InitValidiator(valUsernameReq, username, RequiredErrorMessage);

            valUsernameFormat = new RegularExpressionValidator();
            InitValidiator(valUsernameFormat, username, UserNameFormatErrorMessage);
            valUsernameFormat.ValidationExpression = UsernameValidationExpression;

            password = InitTextBox("password");
            password.TextMode = TextBoxMode.Password;

            valPasswordReq = new RequiredFieldValidator();
            InitValidiator(valPasswordReq, password, RequiredErrorMessage);

            valPasswordFormat = new RegularExpressionValidator();
            InitValidiator(valPasswordFormat, password, PasswordFormatErrorMessage);
            valPasswordFormat.ValidationExpression = PasswordValidationExpression;
            this.Controls.Add(valPasswordFormat);

            confirmPassword = InitTextBox("confirmPassword");
            confirmPassword.TextMode = TextBoxMode.Password;

            valConfirmPasswordReq = new RequiredFieldValidator();
            InitValidiator(valConfirmPasswordReq, confirmPassword, RequiredErrorMessage);

            valConfirmPasswordMatch = new CompareValidator();
            InitValidiator(valConfirmPasswordMatch, confirmPassword, "Passwords do not match.");
            valConfirmPasswordMatch.ControlToCompare = password.ID;
            valConfirmPasswordMatch.Operator = ValidationCompareOperator.Equal;

            email = InitTextBox("email");

            valEmailReq = new RequiredFieldValidator();
            InitValidiator(valEmailReq, email, RequiredErrorMessage);

            valEmailFormat = new RegularExpressionValidator();
            InitValidiator(valEmailFormat, email, "Invalid Email Address.");
            valEmailFormat.ValidationExpression = EmailValidationExpression;
            this.Controls.Add(valEmailFormat);

            firstName = InitTextBox("firstName");

            valFirstNameReq = new RequiredFieldValidator();
            InitValidiator(valFirstNameReq, firstName, RequiredErrorMessage);

            lastName = InitTextBox("lastName");

            valLastNameReq = new RequiredFieldValidator();
            InitValidiator(valLastNameReq, lastName, RequiredErrorMessage);

            dateOfBirth = InitTextBox("dateOfBirth");

            valDOBReq = new RequiredFieldValidator();
            InitValidiator(valDOBReq, dateOfBirth, RequiredErrorMessage);

            valDOBRange = new RangeValidator();
            InitValidiator(valDOBRange, dateOfBirth, "Invalid Date of Birth");
            valDOBRange.MinimumValue = DateTime.Today.AddYears(-100).ToString("yyyy/MM/dd");
            valDOBRange.MaximumValue = DateTime.Today.AddYears(-1).ToString("yyyy/MM/dd");
            valDOBRange.CultureInvariantValues = true;
            valDOBRange.Type = ValidationDataType.Date;

            genderMale = new RadioButton();
            InitControl(genderMale, "male");
            genderMale.GroupName = string.Concat(this.ClientID, "gender");

            genderFemale = new RadioButton();
            InitControl(genderFemale, "female");
            genderFemale.GroupName = string.Concat(this.ClientID, "gender");

            valGenderReq = new Acms.WebControls.CheckedRequiredValidator();
            InitValidiator(valGenderReq, genderMale, RequiredErrorMessage);
            valGenderReq.ControlsToValidate = new string[] { genderMale.ID, genderFemale.ID };

            address1 = InitTextBox("address1");
            valAddress1Req = new RequiredFieldValidator();
            InitValidiator(valAddress1Req, address1, RequiredErrorMessage);

            address2 = InitTextBox("address2");

            town = InitTextBox("town");
            valTownReq = new RequiredFieldValidator();
            InitValidiator(valTownReq, town, RequiredErrorMessage);

            postCode = InitTextBox("postCode");
            valPostCodeReq = new RequiredFieldValidator();
            InitValidiator(valPostCodeReq, postCode, RequiredErrorMessage);

            mobile = InitTextBox("mobile");

            valMobileReq = new RequiredFieldValidator();
            InitValidiator(valMobileReq, mobile, RequiredErrorMessage);

            btnSave = new Button();
            btnSave.ID = "btnSave";
            btnSave.Text = "Save";
            btnSave.ValidationGroup = this.ClientID;
            btnSave.Click += new EventHandler(btnSave_Click);
            this.Controls.Add(btnSave);

            btnEdit = new Button();
            btnEdit.CausesValidation = false;
            btnEdit.Text = "Edit these details";
            btnEdit.Click += new EventHandler(btnEdit_Click);
            this.Controls.Add(btnEdit);

            if (CustomFields != null)
            {
                customFieldsContainer = new PlaceHolder();
                this.Controls.Add(customFieldsContainer);
                CustomFields.InstantiateIn(customFieldsContainer);
            }

            base.CreateChildControls();
        }

        void btnEdit_Click(object sender, EventArgs e)
        {
            currentMode = Mode.Edit;
        }

        void btnSave_Click(object sender, EventArgs e)
        {

        }



        private TextBox InitTextBox(string id)
        {
            TextBox tmp = new TextBox();
            InitControl(tmp, id);
            return tmp;
        }

        private void InitControl(Control ctrl, string id)
        {
            ctrl.ID = id;
            this.Controls.Add(ctrl);
        }

        private void InitValidiator(BaseValidator val, Control controlToValidate, string errorMessage)
        {
            val.ErrorMessage = errorMessage;
            val.ControlToValidate = controlToValidate.ID;
            val.ValidationGroup = this.ClientID;
            val.Display = ValidatorDisplay.Dynamic;
            this.Controls.Add(val);
        }

        protected override void OnPreRender(EventArgs e)
        {
            EnsureChildControls();
            if (requiresDataBinding)
            {
                DataBind();
            }
            base.OnPreRender(e);
        }

        public override void DataBind()
        {
            requiresDataBinding = false;
            if (Page != null && Page.Request != null && Page.Request.IsAuthenticated)
            {
                if (Page.User.Identity is Acms.Bll.UserIdentity)
                {
                    Acms.Bll.User user = ((Acms.Bll.UserIdentity)Page.User.Identity).User;
                    username.Text = user.UserName;
                    email.Text = user.EmailAddress;
                    firstName.Text = user.FirstName;
                    lastName.Text = user.LastName;
                    address1.Text = user.Address1;
                    address2.Text = user.Address2;
                    town.Text = user.Town;
                    postCode.Text = user.PostCode;
                    mobile.Text = user.MobileTel;
                }
            }
            else if (Page != null && Page.Request != null && !Page.Request.IsAuthenticated)
            {
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
            }
            
        }

        bool duplicateEmail = false;
        bool duplicateUsername = false;
        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (Page != null && Page.Request != null && !Page.Request.IsAuthenticated)
            {
                return;
            }
            else
            {
                //wrapper div
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "register");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);

                if (duplicateEmail || duplicateUsername)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, ErrorMessageClass);
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    if (duplicateEmail)
                    {
                        writer.RenderBeginTag(HtmlTextWriterTag.Span);
                        writer.Write("This email address belongs to another user.");
                        writer.RenderEndTag();
                    }
                    if (duplicateUsername)
                    {
                        writer.RenderBeginTag(HtmlTextWriterTag.Span);
                        writer.Write("This username belongs to another user.");
                        writer.RenderEndTag();
                    }
                    writer.RenderEndTag();
                }
                //render ul
                writer.RenderBeginTag(HtmlTextWriterTag.Ul);

                RenderUsername(writer);
                RenderPassword(writer);
                RenderConfrimPassword(writer);
                RenderEmail(writer);
                RenderFirstName(writer);
                RenderLastName(writer);
                RenderDateOfBirth(writer);
                RenderGender(writer);
                RenderAddress(writer);
                RenderMobile(writer);

                if (CustomFields != null)
                {
                    customFieldsContainer.RenderControl(writer);
                }

                RenderItemWrapperStart(writer, "button");
                if (CurrentMode == Mode.Edit)
                {
                    btnSave.RenderControl(writer);
                }
                else
                {
                    btnEdit.RenderControl(writer);
                }
                RenderItemWrapperEnd(writer);

                writer.RenderEndTag();

            }
        }

        private void RenderUsername(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "username");
            RenderLabel("Username:", username, "username", writer);
            if (CurrentMode == Mode.Edit)
            {
                username.RenderControl(writer);
                valUsernameReq.RenderControl(writer);
                valUsernameFormat.RenderControl(writer);
            }
            else
            {
                RenderDisplayLabel(username.Text, "username", writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderPassword(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "password");
            RenderLabel("Password:", password, "password", writer);
            if (CurrentMode == Mode.Edit)
            {
                password.RenderControl(writer);
                valPasswordReq.RenderControl(writer);
                valPasswordFormat.RenderControl(writer);
            }
            else
            {
                RenderDisplayLabel("xxxxxxxxx", "password", writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderConfrimPassword(HtmlTextWriter writer)
        {
            if (CurrentMode == Mode.Edit)
            {
                RenderItemWrapperStart(writer, "confirmPassword");
                RenderLabel("Confirm Password:", confirmPassword, "confirmPassword", writer);
                confirmPassword.RenderControl(writer);
                valConfirmPasswordReq.RenderControl(writer);
                valConfirmPasswordMatch.RenderControl(writer);
                RenderItemWrapperEnd(writer);
            }
        }

        private void RenderEmail(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "email");
            RenderLabel("Email:", email, "email", writer);
            if (CurrentMode == Mode.Edit)
            {
                email.RenderControl(writer);
                valEmailReq.RenderControl(writer);
                valEmailFormat.RenderControl(writer);
            }
            else
            {
                RenderDisplayLabel(email.Text, "email", writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderFirstName(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "firstname");
            RenderLabel("First Name:", firstName, "firstname", writer);
            if (CurrentMode == Mode.Edit)
            {
                firstName.RenderControl(writer);
                valFirstNameReq.RenderControl(writer);
            }
            else
            {
                RenderDisplayLabel(firstName.Text, "firstname", writer);
            }
            RenderItemWrapperEnd(writer);
        }


        private void RenderLastName(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "lastName");
            RenderLabel("Last Name:", lastName, "lastName", writer);
            if (CurrentMode == Mode.Edit)
            {
                lastName.RenderControl(writer);
                valLastNameReq.RenderControl(writer);
            }
            else
            {
                RenderDisplayLabel(lastName.Text, "lastname", writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderDateOfBirth(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "dob");
            RenderLabel("Date of Birth:", dateOfBirth, "dob", writer);
            System.Globalization.CultureInfo info = System.Globalization.CultureInfo.CurrentCulture;
            if (CurrentMode == Mode.Edit)
            {
                dateOfBirth.RenderControl(writer);
                writer.Write("({0})", info.DateTimeFormat.ShortDatePattern.Replace("M", "m"));
                valDOBReq.RenderControl(writer);
                valDOBRange.RenderControl(writer);
            }
            else
            {
                RenderDisplayLabel(dateOfBirth.Text ,"dob", writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderGender(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "gender");
            if (CurrentMode == Mode.Edit)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.Write("Gender:");
                writer.RenderEndTag();
                RenderLabel("Male", genderMale, "gender", writer);
                genderMale.RenderControl(writer);
                RenderLabel("Female", genderFemale, "gender", writer);
                genderFemale.RenderControl(writer);
                valGenderReq.RenderControl(writer);
            }
            else
            {
                if (genderMale.Checked)
                    RenderDisplayLabel("Male", "gender", writer);
                else
                    RenderDisplayLabel("Female", "gender", writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderAddress(HtmlTextWriter writer)
        {
            if (CurrentMode == Mode.Edit)
            {
                RenderItemWrapperStart(writer, "address1");
                RenderLabel("Address (Line 1):", lastName, "address1", writer);
                address1.RenderControl(writer);
                valAddress1Req.RenderControl(writer);
                RenderItemWrapperEnd(writer);

                RenderItemWrapperStart(writer, "address2");
                RenderLabel("Address (Line 2):", lastName, "address2", writer);
                address2.RenderControl(writer);
                RenderItemWrapperEnd(writer);

                RenderItemWrapperStart(writer, "town");
                RenderLabel("Town / City:", lastName, "town", writer);
                town.RenderControl(writer);
                valTownReq.RenderControl(writer);
                RenderItemWrapperEnd(writer);

                RenderItemWrapperStart(writer, "postcode");
                RenderLabel("PostCode:", lastName, "postCode", writer);
                postCode.RenderControl(writer);
                valPostCodeReq.RenderControl(writer);
                RenderItemWrapperEnd(writer);
            }
            else
            {
                RenderItemWrapperStart(writer, "address");
                RenderLabel("Address", null, "address", writer);
                StringBuilder tmp = new StringBuilder();
                tmp.Append(address1.Text);
                tmp.Append("<br/>");
                tmp.Append(address2.Text);
                tmp.Append("<br/>");
                tmp.Append(town.Text);
                tmp.Append("<br/>");
                tmp.Append(postCode.Text);
                string tmpAddress = tmp.ToString();
                while(tmpAddress.Contains("<br/><br/>"))
                    tmpAddress = tmpAddress.Replace("<br/><br/>", "<br/>");
                while (tmpAddress.StartsWith("<br/>"))
                    tmpAddress = tmpAddress.Substring(5);

                writer.AddAttribute(HtmlTextWriterAttribute.Id, string.Concat(this.ClientID, "_address"));
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.Write(tmpAddress);
                writer.RenderEndTag();
                RenderItemWrapperEnd(writer);

            }
        }

        private void RenderMobile(HtmlTextWriter writer)
        {
            RenderItemWrapperStart(writer, "mobile");
            RenderLabel("Mobile:", lastName, "mobile", writer);
            if (CurrentMode == Mode.Edit)
            {
                mobile.RenderControl(writer);
                valMobileReq.RenderControl(writer);
            }
            else
            {
                RenderDisplayLabel(mobile.Text, "mobile", writer);
            }
            RenderItemWrapperEnd(writer);
        }

        private void RenderItemWrapperStart(HtmlTextWriter writer, string cssClass)
        {
            string tmp = string.Concat("register ", cssClass);
            writer.AddAttribute(HtmlTextWriterAttribute.Class, tmp.Trim());
            writer.RenderBeginTag(HtmlTextWriterTag.Li);

        }

        private void RenderItemWrapperEnd(HtmlTextWriter writer)
        {
            writer.RenderEndTag();
        }


        private void RenderLabel(string text, Control associatedControl, string name, HtmlTextWriter writer)
        {
            if (CurrentMode == Mode.Edit)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.For, associatedControl.ClientID);
            }
            else
            {
                writer.AddAttribute(HtmlTextWriterAttribute.For, string.Concat(this.ClientID, "_", name));
            }
            writer.RenderBeginTag(HtmlTextWriterTag.Label);
            writer.Write(text);
            writer.RenderEndTag();
        }

        private void RenderDisplayLabel(string value, string name, HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Id, string.Concat(this.ClientID, "_", name));
            writer.RenderBeginTag(HtmlTextWriterTag.Span);
            writer.Write(value);
            writer.RenderEndTag();
        }*/

    }
}
